#include <stdio.h>

typedef struct {
	char name[32];
	unsigned age;
	long id;
} Student;


void test1(const char *path, const char *w_mode, const char *r_mode) {
	FILE* fp = NULL;
	unsigned cnt = 0;
	Student stu1 = { "WangTeacher", 18, 123456 };
	Student stu2 = { 0 };

	fp = fopen(path, w_mode);
	if (NULL == fp) {
		return;
	}
	cnt = fwrite((void*)(&stu1), sizeof(Student), 1, fp);
	fclose(fp);
	printf("write cnt = %u\n", cnt);

	fp = fopen(path, r_mode);
	if (NULL == fp) {
		return;
	}
	cnt = fread((void*)(&stu2), sizeof(Student), 1, fp);
	fclose(fp);
	printf("read cnt = %u\n", cnt);
	printf("stu2 >> %s %u %ld\n", stu2.name, stu2.age, stu2.id);
}

void test2(const char* path, const char* w_mode, const char* r_mode) {
	FILE* fp = NULL;
	unsigned cnt = 0;
	unsigned i = 0;
	Student studs[3] = {
		{"xiaoming", 7, 1000},
		{"zhangsan", 8, 1001},
		{"lisi", 6, 1002}
	};
	Student studs_in[3] = { 0 };

	fp = fopen(path, w_mode);
	if (NULL == fp) {
		return;
	}
	cnt = fwrite((void*)studs, sizeof(Student), 3, fp);
	//fflush(fp);
	fclose(fp);
	printf("write cnt = %u\n", cnt);

	fp = fopen(path, r_mode);
	if (NULL == fp) {
		return;
	}
	cnt = fread((void*)studs_in, sizeof(Student), 3, fp);
	fclose(fp);
	printf("read cnt = %u\n", cnt);
	for (i = 0; i < 3; i++) {
		printf("%s %u %ld\n", studs_in[i].name, studs_in[i].age, studs_in[i].id);
	}
}

int main() {
	test1("student1.txt", "w", "r");
	printf("================================\n");
	test1("student1.bin", "wb", "rb");
	printf("================================\n");
	test2("student2.txt", "w", "r");
	printf("================================\n");
	test2("student2.bin", "wb", "rb");
	return 0;
}